package com.ab.example.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.ab.abrpc.model.RpcRequest;
import com.ab.abrpc.model.RpcResponse;
import com.ab.abrpc.serializer.JdkSerializer;
import com.ab.abrpc.serializer.Serializer;
import com.ab.example.common.model.User;
import com.ab.example.common.service.UserService;

import java.io.IOException;

public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        Serializer serializer = new JdkSerializer();
        RpcRequest request=RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        try {
            byte[] serialize = serializer.serialize(request);
            byte[]result;
            try(HttpResponse httpResponse= HttpRequest.post("http://localhost:8080")
                    .body(serialize)
                    .execute()){
                result=httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result,RpcResponse.class);
            return (User)rpcResponse.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
